package com.maimao.core.utils;

import com.alibaba.fastjson.JSON;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.Arrays;
import java.util.List;

public class PinYinUtils {
    /**
     * 如： 输入 手机/运营商/数码  输出： ["shŏujī","yùnyíngshāng","shùmă"]
     */
    public static String getPingYin2Json(String inputString, String split) {
        String pingYin = getPinYin(inputString);
        if (split != null) {
            List<String> pyList = Arrays.asList(pingYin.split(split));
            return JSON.toJSONString(pyList);
        }
        return null;
    }

    /**
     * 如： 输入 手机/运营商/数码  输出： ["S","Y","S"]
     */
    public static String getPingYinHead2Json(String inputString, String split) {
        String pingYin = getPinYin(inputString);
        if (split != null) {
            List<String> pyList = Arrays.asList(pingYin.split(split));
            for (int i = 0; i < pyList.size(); i++) {
                pyList.set(i,pyList.get(i).substring(0,1).toUpperCase())     ;
            }
            return JSON.toJSONString(pyList);
        }
        return null;
    }


    public static String getPinYin(String inputString) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
        String output = "";
        if (inputString != null && inputString.length() > 0
                && !"null".equals(inputString)) {
            char[] input = inputString.trim().toCharArray();
            try {
                for (int i = 0; i < input.length; i++) {
                    if (java.lang.Character.toString(input[i]).matches(
                            "[\\u4E00-\\u9FA5]+")) {
                        String[] temp = PinyinHelper.toHanyuPinyinStringArray(
                                input[i], format);
                        output += temp[0];
                    } else {
                        output += java.lang.Character.toString(input[i]);
                    }
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.printStackTrace();
            }
        } else {
            return "*";
        }
        return output;
    }

    public static String getHead(String brandName) {
        return getPinYin(brandName).substring(0,1);
    }
}
